import { DependencyContainer } from "tsyringe";
import { useBuild, useData } from '@sker/runtime'
import { z } from "zod";
import { HttpError, ROOT, toSuccess, watchAddon } from "@sker/core";
import { ExecOptions, exec } from "child_process";
import { join } from "path";
export default async (container: DependencyContainer) => {
    const root = container.resolve(ROOT)
    const input = z.object({
        name: z.optional(z.string())
    })
    const body = input.parse(useData())
    if (body.name !== 'all') {
        const [scope, addon] = body.name.split('/')
        if (!scope || !addon) {
            throw new HttpError(`scope或者addon为空`)
        }
        const isWatch = false;
        await awaitExec('pnpm run tsc', { cwd: join(root, `addons/${scope}/${addon}`) })
        await watchAddon(scope.replace('@', '').trim(), addon.trim(), isWatch)
        return toSuccess(true)
    } else {

    }
}

export const awaitExec = async (command: string, options: ExecOptions = {}) => {
    return new Promise<void>((resolve, reject) => {
        const root = process.cwd();
        const npmInstall = exec(command, { cwd: root, ...options })
        npmInstall.on('close', () => resolve())
        npmInstall.on('error', (e) => reject(e))
        npmInstall.stdout.pipe(process.stdout)
    })
}